const express = require('express')
const route = express.Router()
const path = require('path')
const fs = require('fs')
//引入数据库文件
const advModel = require('../db/model/addAdvModel')
//引入权限校验文件
const isLoginMiddle = require('../middleware/isLoginMiddle')

route.delete('/deleteAdv', isLoginMiddle, async (req, res) => {
  //console.log('测试');
  const { _id } = req.query
  //console.log(_id, '_id');
  //删除数据库对应的图片
  //首先去数据库查找id对应的图片
  try {
    const { advHref } = await advModel.findOne({
      _id
    })
    //console.log(advHref, 'advHref');// /upload/7634b6d28b7a3d127e2073700.jpg
    const imgName = advHref.split('/')[2]
    //console.log(imgName, 'imgName');
    //删除这个图片
    fs.unlink(path.resolve(__dirname, '../upload', imgName), () => {
      console.log('删除图片成功');
    })
  } catch (e) {
    console.log("删除图片错误" + e.message);
    return res.send({
      code: 10001,
      mesage: "删除图片错误" + e.message,
      data: null
    })
  }
  //删除数据库数据
  try {
    await advModel.deleteOne({
      _id
    })
    res.send({
      code: 10000,
      mesage: '删除广告成功',
      data: null
    })
  } catch (e) {
    console.log('删除广告成功', e.message);
    res.send({
      code: 10001,
      mesage: '删除广告失败' + e.message,
      data: null
    })
  }
})

module.exports = route